#pragma once

#include "logger.hpp"
#include <iostream>

class ErrStream : public std::streambuf {
private:
    const std::size_t _bufferSize;
    char *_buffer;

public:
    ErrStream(std::size_t bufferSize)
        : _bufferSize(bufferSize), _buffer(new char[_bufferSize]) {
        setp(_buffer, _buffer + _bufferSize);
    }

    ~ErrStream() {
        delete[] _buffer;
    }

protected:
    int sync() override {
        error("{}", std::string_view(pbase(), pptr() - pbase() - 1));
        setp(_buffer, _buffer + _bufferSize);
        pbump(0);
        return 0;
    }

    int overflow(int ch) override {
        sync();
        if (ch != EOF) {
            sputc(traits_type::to_char_type(ch));
        }

        return traits_type::not_eof(ch);
    }
};
